<template>
  <div class="app-container" style="padding: 0;">
    <div class="top-title-border top-title-background" style="height: 50px;padding: 5px 0;">
      <i class="el-icon-back"
        style="color: #ffffff;width:5%;height: 40px;display: inline-block;font-size: 20px;line-height: 40px;padding-left: 20px;cursor: pointer;z-index: 2;position: relative;"
        @click="goBack"></i>
      <span
        style="position: absolute;top:0;left: 0;right: 0;z-index: 1;text-align: center;color: #ffffff;font-size: 22px;font-weight: bold;line-height: 50px;">{{
          device != null ? device.deptName : template.templateName }}</span>
      <div v-if="device != null" style="font-size: 14px;font-weight: bold;color: #ffffff;display: inline">
        <div class="info-box">
          <span>监测油品：</span>
          <dict-tag style="display: inline;" :options="dict.type.oil_code" :value="device.oilCode" />
        </div>
        <div class="info-box">
          <span>设备名称：{{ device.name }}</span>
        </div>
      </div>
    </div>

    <div class="top-title-background" style="display: flex;justify-content: space-between;padding-left: 10px;">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="" prop="variableName" style="width: 160px;">
          <el-select v-model="queryParams.variableName" placeholder="监测指标" clearable>
            <el-option v-for="variable in variableList" :key="variable.id" :label="variable.name"
              :value="variable.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="alarmLevel" style="width: 160px;">
          <el-select v-model="queryParams.alarmLevel" placeholder="报警等级" clearable>
            <el-option v-for="dict in dict.type.oil_alarm_level" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="state" style="width: 160px;">
          <el-select v-model="queryParams.state" placeholder="是否开启" clearable>
            <el-option v-for="dict in dict.type.oil_yes_no" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <i class="el-icon-search icon" @click="handleQuery"></i>
          <i class="el-icon-refresh icon" @click="resetQuery"></i>
        </el-form-item>
      </el-form>
      <div style="display: inline-block;margin-top: 5px;">
        <el-button type="primary" class="button" size="mini" @click="addRow" style="margin-right: 10px;"
          v-hasPermi="['oil:rule:add']">新增</el-button>
        <el-button v-if="device" type="primary" class="button" size="mini" @click="open=true" style="margin-right: 10px;"
          v-hasPermi="['oil:rule:add']">从模板新增</el-button>
        <el-button type="primary" class="button" size="mini" @click="handleExport" style="margin-right: 10px;"
          v-hasPermi="['oil:rule:export']">导出</el-button>
        <!--<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['oil:rule:edit']">修改</el-button>
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['oil:rule:remove']">删除</el-button>
           -->
      </div>
    </div>
    <div style="padding: 20px 20px 5px;">
      <span style="color: #ffffff;font-size: 16px;font-weight: bold;letter-spacing: 2px;margin-right: 20px;">报警规则</span>
      <span
        style="color: #d1d1d1;font-size: 14px;font-weight: bold;letter-spacing: 1px;margin-right: 20px;">预警规则：根据不同监测指标设置触发条件，设定上下触发规则</span>
      <span
        style="color: #d1d1d1;font-size: 14px;font-weight: bold;letter-spacing: 1px;">等级规则：数据异常时根据由高到低顺序对等级预警规则逐级判断，直至符合某一等级的触发条件</span>
    </div>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :visible.sync="open" :title="title" width="60%" @close="close">
      <el-form :inline="true" :model="templateQuery" ref="templateQueryForm" size="small">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="templateQuery.templateName" placeholder="模板名称" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceTypeName">
          <el-input v-model="templateQuery.deviceTypeName" placeholder="设备类型" />
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getTemplateList">查询</el-button>
      </el-form>
      <el-table :data="templateList" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="模板名称" align="center" prop="templateName">
        </el-table-column>
        <el-table-column label="设备类型" align="center" prop="deviceTypeName">
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
        </el-table-column>
      </el-table>
      <pagination
      v-show="templateTotal>0"
      :total="templateTotal"
      :page.sync="templateQuery.pageNum"
      :limit.sync="templateQuery.pageSize"
      @pagination="getTemplateList"
    />
      <div>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>

    </el-dialog>

    <!-- 添加或修改报警规则对话框 -->
    <el-form ref="form" class="table-form" size="small" :model="form" :rules="rules">
      <el-table :data="form.alarmRules">
        <el-table-column label="监测指标" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.show" :prop="'alarmRules.' + scope.$index + '.variableKey'"
              :rules="rules.variableKey">
              <el-select v-model="form.alarmRules[scope.$index].variableKey" placeholder="监测指标" clearable>
                <el-option v-for="variable in variableList" :key="variable.id" :label="variable.name"
                  :value="variable.key"></el-option>
              </el-select>
            </el-form-item>
            <div v-else>{{ scope.row.variableName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="报警等级" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.show" :prop="'alarmRules.' + scope.$index + '.alarmLevel'"
              :rules="rules.alarmLevel">
              <el-select v-model="form.alarmRules[scope.$index].alarmLevel" placeholder="报警等级" clearable>
                <el-option v-for="dict in dict.type.oil_alarm_level" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <div v-else>
              <dict-tag :options="dict.type.oil_alarm_level" :value="scope.row.alarmLevel" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="触发条件" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.show" :prop="'alarmRules.' + scope.$index + '.alarmType'"
              :rules="rules.alarmType">
              <el-select v-model="form.alarmRules[scope.$index].alarmType" placeholder="请选择触发条件"
                @change="alarmTypeChange(scope)">
                <el-option v-for="dict in dict.type.oil_alarm_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <div v-else><dict-tag :options="dict.type.oil_alarm_type" :value="scope.row.alarmType" /></div>
          </template>
        </el-table-column>
        <el-table-column label="上限阈值" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.show" :prop="'alarmRules.' + scope.$index + '.maxValue'">
              <el-input type="number" v-model="form.alarmRules[scope.$index].maxValue" placeholder=">X"
                :disabled="scope.row.alarmType == 2" />
            </el-form-item>
            <div v-else>{{ scope.row.maxValue }}</div>
          </template>
        </el-table-column>
        <el-table-column label="下限阈值" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.show" :prop="'alarmRules.' + scope.$index + 'minValue'">
              <el-input type="number" v-model="form.alarmRules[scope.$index].minValue" placeholder="<Y"
                :disabled="scope.row.alarmType == 0" />
            </el-form-item>
            <div v-else>{{ scope.row.minValue }}</div>
          </template>
        </el-table-column>
        <el-table-column label="报警信息" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.show" :prop="'alarmRules.' + scope.$index + '.message'"
              :rules="rules.message">
              <el-input v-model="form.alarmRules[scope.$index].message" placeholder="请输入报警信息" />
            </el-form-item>
            <div v-else>{{ scope.row.message }}</div>
          </template>
        </el-table-column>
        <el-table-column label="维护建议" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.show" :prop="'alarmRules.' + scope.$index + '.remark'">
              <el-input v-model="form.alarmRules[scope.$index].remark" placeholder="请输入维护建议" />
            </el-form-item>
            <div v-else>{{ scope.row.remark }}</div>
          </template>
        </el-table-column>
        <el-table-column label="推送方式" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.show" :prop="'alarmRules.' + scope.$index + '.noticeType'"
              :rules="rules.noticeType">
              <el-select v-model="form.alarmRules[scope.$index].noticeType" placeholder="请选择推送方式"
                @change="noticeTypeChange(scope)">
                <el-option v-for="dict in dict.type.oil_notic_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <div v-else>
              <dict-tag :options="dict.type.oil_notic_type" :value="scope.row.noticeType" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="推送人员" align="center" width="200px">
          <template slot-scope="scope">
            <el-form-item :prop="'alarmRules.' + scope.$index + '.sendUserIds'" class="tree-sel">
              <el-select v-if="scope.row.noticeType != 1" multiple v-model="form.alarmRules[scope.$index].sendUserIds"
                placeholder="请选择推送人员">
                <el-option v-for="user in userList" :key="user.userId" :label="user.userName"
                  :disabled="!scope.row.show" :value="user.userId"></el-option>
              </el-select>
              <treeselect v-else multiple :appendToBody="true" z-index="9999"
                v-model="form.alarmRules[scope.$index].sendDeptIds" :options="deptOptions" placeholder="请选择推送部门"
                :show-count="true" :disabled="!scope.row.show" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center">
          <template slot-scope="scope">
            <el-form-item v-if="scope.row.show" :prop="'alarmRules.' + scope.$index + 'order'">
              <el-input type="number" v-model="form.alarmRules[scope.$index].order" placeholder="排序" />
            </el-form-item>
            <div v-else>{{ scope.row.order }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.show" @click="handleUpdate(scope)" size="mini" type="text">修改</el-button>
            <el-button v-if="scope.row.show" @click="submitForm(scope)" size="mini" type="text">保存</el-button>
            <el-button v-if="scope.row.show && scope.row.id != null" @click="cancelEdit(scope.$index)" size="mini"
              type="text">取消</el-button>
            <el-button @click="handleDelete(scope)" size="mini" type="text">删除</el-button>
            <el-button v-if="device && !scope.row.show && scope.row.state == 0" type="primary" @click="handleStateOpen(scope)"
              size="mini" style="border-radius: 0;height: 25px;">开启</el-button>
            <el-button v-if="device && !scope.row.show && scope.row.state == 1" type="info" @click="handleStateClose(scope)"
              size="mini" style="border-radius: 0;height: 25px;">关闭</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
import { listRule, getRule, delRule, addRule, updateRule, addRulesByTemplate } from "@/api/oil/rule";
import { getDeviceByCode } from "@/api/oil/device";
import { getTemplate, listTemplate } from "@/api/oil/template";
import { listVariable } from "@/api/oil/variable";
import { listUser, deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  name: "Rule",
  dicts: ['oil_alarm_type', 'oil_notic_type', 'oil_code', 'oil_alarm_level', 'oil_yes_no'],
  components: { Treeselect },
  data() {
    return {
      //本页设备
      device: null,
      //本页模板
      template: null,
      //监测指标列表
      variableList: [],
      variableMap: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceCode: null,
        variableKey: null,
        alarmType: null,
        alarmLevel: null,
        noticeType: null,
        state: null,
      },
      //表单数据
      form: { alarmRules: [] },
      userList: [],
      deptOptions: [],
      rules: {
        variableKey: [{ required: true, message: '请选择监测指标', trigger: 'blur' }],
        alarmLevel: [{ required: true, message: '请选择报警等级', trigger: 'blur' }],
        alarmType: [{ required: true, message: '请选择触发条件', trigger: 'blur' }],
        message: [{ required: true, message: '请输入报警信息', trigger: 'blur' }],
        noticeType: [{ required: true, message: '请选择推送方式', trigger: 'blur' }]
      },
      templateList: [],
      // 模板查询参数
      templateQuery: {
        pageNum: 1,
        pageSize: 10,
        templateName: "",
        deviceTypeId: ""
      },
      templateTotal: 0,
    };
  },
  created() {
    const deviceCode = this.$route.params && this.$route.params.deviceCode;
    const templateId = this.$route.params && this.$route.params.templateId;
    if (deviceCode) {
      getDeviceByCode(deviceCode).then(response => {
        this.device = response.data;
        this.queryParams.deviceId = this.device.id;
        this.getList();
      })
    } else if (templateId) {
      console.log("templateId", templateId);
      getTemplate(templateId).then(response => {
        this.template = response.data;
        this.queryParams.templateId = this.template.id;
        this.getList();
      })
    }
    this.getVariables();
    this.getUserList();
    this.getDeptList();
  },
  mounted() {
    // 如果是从模板跳转过来，则查询模板列表
    const deviceCode = this.$route.params && this.$route.params.deviceCode;
    if (deviceCode) {
      this.getTemplateList();
    }
  },
  methods: {
    getTemplateList() {
      listTemplate(this.templateQuery).then(response => {
        this.templateList = response.rows;
        this.templateTotal = response.total;
        console.log("templateList", this.templateList);
      });
    },
    getUserList() {
      listUser({ pageSize: 5000 }).then(response => {
        this.userList = response.rows;
      })
    },
    getDeptList() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    getVariables() {
      listVariable({ pageSize: 5000 }).then(response => {
        this.variableList = response.rows;
        this.variableMap = new Map(response.rows.map(obj => [obj["key"], obj]))
      })
    },
    /** 查询报警规则列表 */
    getList() {
      this.loading = true;
      listRule(this.queryParams).then(response => {
        var ruleList = response.rows;
        this.form.alarmRules = ruleList.map(obj => {
          if (obj.sendUserIds != null && obj.sendUserIds.length > 0) obj.sendUserIds = obj.sendUserIds.split(",").map(str => { return parseInt(str); });
          else obj.sendUserIds = [];
          if (obj.sendDeptIds != null && obj.sendDeptIds.length > 0) obj.sendDeptIds = obj.sendDeptIds.split(",").map(str => { return parseInt(str); });
          else obj.sendDeptIds = [];
          obj.show = false;
          return obj;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancelEdit(index) {
      // this.form.alarmRules[index].show = false;
      this.getList();
    },
    // 表单重置
    reset() {
      this.form.alarmRules = [{ minValue: "", maxValue: "" }];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    },
    // 校验
    validateField(form, index, row) {
      let result = true;
      for (let item of this.$refs[form].fields) {
        if (item.prop.split(".")[1] == index && item.rules != null && item.rules.length > 0) {
          this.$refs[form].validateField(item.prop, err => {
            if (err != "" && result) {
              result = false;
            }
          });
        }
      }
      if (result) {
        if (row.alarmType == 0 && (row.maxValue == null || row.maxValue == "")) { this.$modal.msgWarning("请将上限阈值填写完整！"); result = false; }
        else if (row.alarmType == 2 && (row.minValue == null || row.minValue == "")) { this.$modal.msgWarning("请将下限阈值填写完整！"); result = false; }
        else if (row.alarmType == 1) {
          if (row.minValue == "" || row.minValue == null || row.maxValue == "" || row.maxValue == null) {
            this.$modal.msgWarning("请将上限阈值与下限阈值填写完整");
            result = false;
          } else if (row.maxValue >= row.minValue) {
            this.$modal.msgWarning(">X且<Y的触发条件下X的值应当小于Y值");
            result = false;
          }
        }
        if (row.noticeType == 0 && (row.sendUserIds == null || row.sendUserIds.length <= 0)) {
          this.$modal.msgWarning("请选择推送人员！")
          result = false;
        }
        if (row.noticeType == 1 && (row.sendDeptIds == null || row.sendDeptIds.length <= 0)) {
          this.$modal.msgWarning("请选择推送部门！")
          result = false;
        }
      }
      console.log(result);
      return result;
    },
    /** 修改按钮操作 */
    handleUpdate(scope) {
      this.form.alarmRules[scope.$index].show = true;
    },
    /** 提交按钮 */
    submitForm(scope) {
      if (this.validateField("form", scope.$index, scope.row)) {
        var data = scope.row;
        console.log(data);
        if (data.sendUserIds != null && data.sendUserIds.length > 0) data.sendUserIds = data.sendUserIds.join(",");
        else data.sendUserIds = "";
        if (data.sendDeptIds != null && data.sendDeptIds.length > 0) data.sendDeptIds = data.sendDeptIds.join(",");
        else data.sendDeptIds = "";
        if (this.device) data.deviceId = this.device.id;
        else if (this.template) data.templateId = this.template.id;
        data.variableName = this.variableMap.get(data.variableKey).name;
        if (scope.row.id != null) {
          updateRule(data).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.getList();
          });
        } else {
          data.state = 1;//新增时规则默认处于开启状态
          addRule(data).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.getList();
          });
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(scope) {
      var row = scope.row;
      if (row.id == null) return this.deleteRow(scope.$index);
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除报警规则编号为"' + ids + '"的数据项？').then(function () {
        return delRule(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oil/rule/export', {
        ...this.queryParams
      }, `rule_${new Date().getTime()}.xlsx`)
    },
    goBack() {
      this.$router.back();
    },
    addRow() {
      this.form.alarmRules.unshift({ minValue: "", maxValue: "", show: true });
    },
    deleteRow(index) {
      this.form.alarmRules.splice(index, 1);
    },
    alarmTypeChange(scope) {
      //大于X触发
      if (scope.row.alarmType == 0) {
        this.form.alarmRules[scope.$index].minValue = ""
      } else if (scope.row.alarmType == 2) { //小于Y触发
        this.form.alarmRules[scope.$index].maxValue = ""
      }
    },
    noticeTypeChange(scope) {
      if (scope.row.noticeType == 0) {
        this.form.alarmRules[scope.$index].sendDeptIds = [];
      } else {
        this.form.alarmRules[scope.$index].sendUserIds = [];
      }
    },
    handleStateOpen(scope) {
      this.form.alarmRules[scope.$index].state = 1;
      this.submitForm(scope);
    },
    handleStateClose(scope) {
      this.form.alarmRules[scope.$index].state = 0;
      this.submitForm(scope);
    },
    close() {
      this.open = false;
      this.resetForm("templateQueryForm");
      this.templateList = [];
      this.getTemplateList();
      this.templateTotal = 0;
    },
    confirm() {
      if (this.templateList.length <= 0) {
        this.$modal.msgWarning("请选择模板");
        return;
      }
      if(this.device) {
        var data = {
          deviceId: this.device.id,
          templateIds: this.templateList.map(item => item.id)
        };
        addRulesByTemplate(data).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.getList();
          this.close();
        });
      }else{
        this.$modal.msgWarning("设备ID无效");
      }
    }
  }
};
</script>
<style>
.info-box {
  float: right;
  margin: 10px;
}

.icon {
  font-size: 16px;
  color: #c9c9c9;
  padding: 0 15px;
  cursor: pointer;
}

.table-form .el-form-item {
  margin-bottom: 0;
}

.tree-sel .vue-treeselect__control {
  line-height: 24px;
  margin-top: 4px;
  border-radius: 4px;
  height: 24px;
}

.tree-sel .vue-treeselect__placeholder,
.tree-sel .vue-treeselect__single-value {
  line-height: 24px;
}
</style>
